package com.ykh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ykh.mapper.VideoMapper;
import com.ykh.pojo.po.User;
import com.ykh.pojo.po.Video;
import com.ykh.pojo.vo.ErrorCode;
import com.ykh.pojo.vo.Result;
import com.ykh.service.UserService;
import com.ykh.service.VideoService;
import com.ykh.util.Constant;
import com.ykh.util.QiniuUtils;
import com.ykh.util.UserThreadLocal;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 图片上传控制器
 */
@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    private QiniuUtils qiniuUtils;

    @Autowired
    VideoMapper videoMapper;

    @Autowired
    UserService userService;

    @ApiOperation("视频图片文件上传接口")
    @PostMapping("/image")
    public Result upload(@RequestParam("image") MultipartFile file, @RequestParam Integer videoId){
        String fileName = UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        String key = qiniuUtils.imageUpload(file, fileName);
        if (key != null){
            String imageUrl = Constant.IMAGE_URL + fileName;
            LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Video::getVideoId, videoId);
            //更新数据库中视频的封面地址
            Video video = videoMapper.selectOne(queryWrapper);
            if(video == null){
                return Result.fail(ErrorCode.NO_EXIST_VIDEO.getCode(),ErrorCode.NO_EXIST_VIDEO.getMsg());
            }
            video.setCoverUrl(imageUrl);
            videoMapper.update(video, queryWrapper);
            return Result.success(imageUrl);
        }
        return Result.fail(ErrorCode.VIDEO_IMG_UPLOAD_FAIL.getCode(), ErrorCode.VIDEO_IMG_UPLOAD_FAIL.getMsg());
    }

    /**
     * 用户头像上传接口
     * @return
     */
    @ApiOperation("用户头像上传接口")
    @PostMapping("/avatar")
    public Result uploadAvatar(@RequestParam MultipartFile avatarImage){
        User user = UserThreadLocal.get();
        if(user == null){
            return Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
        }
        return userService.uploadAvatar(avatarImage, user);
    }
}
